package top.lixunda.commerce.gateway.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 限流，使用限流需要在路由中进行配置
 *
 * @author LiXunda
 * @version time:2019/8/31 19:40
 */
@Configuration
public class ResolverConfig {

    /**
     * IP限流
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(getIpAddress(exchange));
    }

    /**
     * 接口限流， 获取请求地址的uri作为限流的key
     */
    @Bean
    public KeyResolver apiKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 获取真实ip
     *
     * @return 返回真实ip，默认返回192.168.1.1
     */
    private static String getIpAddress(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> ips = headers.get("X-Forwarded-For");
        String ip = "192.168.1.1";
        if (ips != null && ips.size() > 0) {
            ip = ips.get(0);
        }
        return ip;
    }

}
